// pages/home/home.js
const util = require('../../utils/util.js')
const Base64 = require('../../utils/Base64.js')
//const CryptoJS = require('crypto-js')

Page({

  /**
   * 页面的初始数据
   */
  data: {
    productid : "le812Uu9ED",
    token : "version=2022-05-01&res=userid%2F322964&et=1768010813&method=sha1&sign=Nqvzp5G8z%2BVYhU58N62cKVJhfWA%3D",
    
    tabList:['所有设备','在线设备','离线设备'],
    tabNow:0,    //当前选中的tab标签索引

    switchChecked:false,   //开关状态
    voiceState:true,    //声音状态      false消音
    item0:0,
    isplay1: false,     //报警
    item1:0,           //报警时长
    item2:0,           //报警消音时长
    isplay3: false,    //离线
    item3:0,           //离线消音时长
    
    titleList:['866970063380700','869786068140817','869786068245640','866970063395740'],
    //deviceNum:'',      //设备数量
    devicesList:[],
    onlineList:[],
    offlineList:[],
    onlineindex:'',
    offlineindex:'',
    value:[],

    alarmRecordnow:[],

    timer:null,
    timer1:null,
  },
  
  //开关事件
  switchChange(e){
    wx.setStorageSync('switchChecked',e.detail.value)
    this.setData({
      switchChecked:e.detail.value// 开关状态
         
      
    })
    console.log('开关状态',e.detail.value)
  },

  //按键消音
  button(){
    this.setData({
      voiceState:false
    })
    console.log("voiceState=",this.data.voiceState);
  },

  // 扫码事件
  scanCodeEvent: function(){
    var that = this;
    wx.scanCode({
      onlyFromCamera: true,// 只允许从相机扫码
      success(res){
        console.log("扫码成功："+res.result)
        // 扫码成功后  在此处理接下来的逻辑
        var scanTitle = res.result.slice(0,15)
        //console.log("title："+scanTitle.length )
        var onlineList = that.data.onlineList
        var offlineList = that.data.offlineList
        for(var index in onlineList){
          if(that.data.onlineList[index].title === scanTitle){
            that.setData({
              onlineindex:index,
              offlineindex:''
            })
            //console.log("onindex：",index)
          }
        }
        for(var index in offlineList){
          if(that.data.offlineList[index].title === scanTitle){
            that.setData({
              onlineindex:'',
              offlineindex:index
            })
           // console.log("offindex：",index)
          }
        }
        /*
        var device = that.data.devicesList.filter(function(devicesList,index,arrs){return devicesList.title === scanTitle})//扫描设备信息
        that.setData({
          currentdevice:device  //扫描设备信息
        })
        console.log("currentdevice：",that.data.currentdevice)
        
        var staus = that.data.currentdevice.online
        console.log("staus =",that.data.currentdevice.online)
        if(staus == true){
          that.setData({
            currentvalue:that.data.valueList.filter(function(valueList,index,arrs){return valueList.title === scanTitle}) //扫描设备信息
          })

          console.log('在线值',JSON.stringify(that.data.currentvalue))
          
        } */
        wx.navigateTo({
          url: '/pages/datail/datail'   //跳转页面
        })
      }
    })
  },

  //切换不同的tab
  selectTab (e) { 
    this.setData({
        tabNow: e.currentTarget.dataset.id
    })
    //console.log('tabNow=',e.currentTarget.dataset.id)
  },

  // 打开在线设备详情
  gotoOnlinedatail(e){
    var that = this
    //console.log('在线',onlineindex,)
    that.setData({
      onlineindex:e.currentTarget.dataset.id,
      offlineindex:''
    })
    wx.navigateTo({
      url: '/pages/datail/datail'
    })
  },

  // 打开离线设备详情
  gotoOfflinedatail(e){
    var that = this
    //console.log('离线',offindexNow,)
    that.setData({
      offlineindex:e.currentTarget.dataset.id,
      onlineindex:''
    })
    wx.navigateTo({
      url: '/pages/datail/datail'  //+'?currentdevice='+encodeURIComponent(JSON.stringify(currentdevice))
    })
  },

  //token
 /* 
  getToken(){
    const productid = 'le812Uu9ED'
    const accessKey = 'jUsZwR0lW51bW2k3GVFzbw8vS2sP26uLFXOvXb3hecU='
    let res = 'userid' +'/'+ productid
    
    var version = "2018-10-31"     // 参数组版本号
    var et = '1718514632'         //Date.parse(new Date())/1000+3600   // 访问过期时间 expirationTime (有效期为1小时）
    var method = 'sha1'
    access_key = Base64.base64Decode(accessKey) // 对access_key进行base64解码
    console.log('access_key=',access_key)
    // 计算sign
    const org = et+'\n' + method+'\n' + res+'\n' + version
    console.log('org=',org)
    //签名
    let sign_b = CryptoJS.HmacSHA1(org,access_key)
    console.log('sign_b=',sign_b)
    var sign = Base64.base64Encode(sign_b)
    console.log('sign=',sign)
    // url 编码
    res = encodeURIComponent(res)
    sign = encodeURIComponent(sign)
    console.log('res=',res)
    console.log(sign)
    // 拼接token
    const token = `version=${version}&res=${res}&et=${et}&method=${method}&sign=${sign}`
    console.log(token);
  },*/
  
  //获取设备数据
  getDevices() {
    var that = this
    let titleList = that.data.titleList
    let productid = that.data.productid
    let token = that.data.token
    
    var alarmRecordnow = that.data.alarmRecordnow 
    var devicesList = []
    
    if(titleList.length == 0)
    {
      that.setData({               
        switchChecked:false,
      })
      wx.showToast({
        title: '无数据',
        icon: 'error'
      });
    }else
    {
      var titlesStr = titleList.join(',')    //在线设备ID字符串
      //console.log('titlesStr=',titlesStr)
      
      wx.request({
          url: 'https://iot-api.heclouds.com/datapoint/current-datapoints?product_id='+productid+'&device_name='+titlesStr,   //获取在线设备数据流
          header: {
            'content-type': 'application/x-www-form-urlencoded',
            'Authorization': token
          },
          //query:{},
          data: {
            
          },
          method: 'GET',
          success:(res)=>{
            //console.log(res.data.data.devices)
        
            var valueList = res.data.data.devices

            /*var isfirst = that.data.isfirst
            if( isfirst== true){
              var alarmRecordnow = that.data.alarmRecordnow 
            }*/
            
            for (var index in valueList) {
              //初始化报警记录
              if(alarmRecordnow.length != titleList.length){
                var alarmRecorddata = [{
                  isalarm:false,
                  title:valueList[index].title
                }]
                alarmRecordnow = alarmRecordnow.concat(alarmRecorddata)
              }
              //判断在线情况
              var dateNow = new Date()
              var timeNow = Date.parse(dateNow)
              var dateData = new Date(valueList[index].datastreams[1].at)
              var timeData = Date.parse(dateData)
              if((timeNow - timeData)<310000) {
                var online = true
              }else{
                var online = false
              }
              //单个设备数组
              var deviceData = {
                title:valueList[index].title,
                state:valueList[index].datastreams[0].value,
                value:valueList[index].datastreams[1].value,
                updatetime:valueList[index].datastreams[1].at,
                online:online
              }
              //插入所有设备数组
              devicesList = devicesList.concat(deviceData)
            } 
            console.log('记录',alarmRecordnow)
            //console.log("devicesList=",devicesList)   
            //在线设备数组
            let onlineList = devicesList.filter(function(devicesList,index,arrs){return devicesList.online == true})
            //离线设备数组
            let offlineList = devicesList.filter(function(devicesList,index,arrs){return devicesList.online == false})
            that.setData({
              alarmRecordnow:alarmRecordnow,
              devicesList:devicesList,
              offlineList: offlineList,
              onlineList: onlineList,
            })
          }
        })

        console.log('在线设备=',that.data.onlineList)
        console.log('离线设备=',that.data.offlineList)
        //console.log('记录=',that.data.alarmRecordnow)
        //const devices = util.formatTime(new Date())
        
        //wx.setStorageSync('devices', devices)
        //console.log('devices',wx.getStorageSync('devices'))
        //console.log(devices)
      }
  }, 

  alarmRecordInit(){
    var alarmRecord = wx.getStorageSync('alarmRecord')
    //console.log(alarmRecord)
    if(alarmRecord.length == 0){
      alarmRecord = []
      wx.setStorageSync('alarmRecord',alarmRecord)
    }
    //console.log("报警记录",wx.getStorageSync('alarmRecord'))
  },
  
  getalarmRecord(){
    console.log("记录：",wx.getStorageSync('alarmRecord'))
  },

  //报警记录
  alarmRecord(){
    var that = this
    var devicesList = that.data.devicesList
    var alarmRecordnow = that.data.alarmRecordnow
    
    //console.log('devicesList:',devicesList)
    //console.log('alarmRecordnow:',alarmRecordnow)
    
    for(var index in devicesList){
      if(devicesList[index].online == true){
        if((devicesList[index].state ==1 || devicesList[index].state ==2)&& alarmRecordnow[index].isalarm == false ){
          alarmRecordnow[index].start = devicesList[index].updatetime,
          alarmRecordnow[index].isalarm = true
        }
        if(devicesList[index].state ==0 && alarmRecordnow[index].isalarm == true){
          alarmRecordnow[index].end = devicesList[index].updatetime
          alarmRecordnow[index].isalarm = false
          //console.log('alarm:',alarmRecordnow[index])
          let alarmRecord = wx.getStorageSync('alarmRecord')
          alarmRecord = alarmRecord.concat(alarmRecordnow[index])
          wx.setStorageSync('alarmRecord',alarmRecord)
        }
      }
    }
    that.setData({
      alarmRecordnow:alarmRecordnow
    })
    //console.log("报警记录：",wx.getStorageSync('alarmRecord'))
  },

   //离线通知
   offlineInform(){
    var that = this
    var isplay3 = that.data.isplay3
    var item3 = that.data.item3
    var devicesList = that.data.devicesList
    var offlineList = that.data.offlineList
    //console.log(offlineList.length)
    if(offlineList.length == 0){
      that.setData({
        isplay3:false,
        item3:0
      })
      //console.log("复位");
    }else{
      for(var index in devicesList){
        if(devicesList[index].online == false && isplay3 == false){
          that.audioPlay(3)
          isplay3 = true
          //console.log('离线通知了')
        }
      }
      if(isplay3 == true){
        item3 = item3 + 1
        //console.log("item3=",item3);
        if(item3 == 1800 ){
          isplay3 = false
          item3 = 0
        }
        that.setData({
          isplay3:isplay3,
          item3:item3
        })
      } 
      //console.log("isplay3=",isplay3,"item3=",item3);
    }
  },

  //报警通知
  alramInform(){
    var that = this
    var voiceState = that.data.voiceState
    var isplay1 = that.data.isplay1
    let alarmRecord = wx.getStorageSync('alarmRecord')
    
    var item1 = that.data.item1
    var item2 = that.data.item2
    var onlineList = that.data.onlineList
    var filterNum1 = onlineList.filter(function(onlineList,index,arrs){return onlineList.state == '1'})
    var filterNum2 = onlineList.filter(function(onlineList,index,arrs){return onlineList.state == '2'})
    var filterNum = filterNum1.concat(filterNum2)
    //console.log('filterNum',filterNum)
    if(filterNum.length == 0){
      //无报警
      that.setData({
        isplay1:false,
        voiceState:true,
        item0:0,
        item1:0,
        item2:0,
      })
      //console.log("复位");
    }else{
      
      if(voiceState == false){   //消音
        isplay1 = true
        item1 = 0
        that.setData({
          item1:item1,
          voiceState: true,
        })
      }
      if(isplay1 == false){
        if(item1%2 == 0){
          that.audioPlay(1)
        //console.log('报警通知了')
        }

        item1 = item1 + 1
        
        /*if(item1 == 1){
          alarmRecord = alarmRecord.concat(filterNum)
          wx.setStorageSync('alarmRecord',alarmRecord)
          //console.log('filterNum1',filterNum1)
          //console.log('报警记录',wx.getStorageSync('alarmRecord')) 
        }*/

        if(item1 == 30){
          isplay1 = true
          item1 = 0
        }
        that.setData({
          item1:item1
        })
        //console.log('item1=',item1)
      }
      if(isplay1 == true){
        item2 = item2 + 1
        //console.log("item3=",item3);
        if(item2 == 600 ){    //600s重新报警
          isplay1 = false
          item2 = 0
        }
        that.setData({
          isplay1:isplay1,
          item2:item2
        })
      } 
      //console.log("item1=",item1,"item2=",item2,"isplay1=",isplay1,);
    }
  },

  //播放音频
  audioPlay(key) {
    //创建内部 audio 上下文 InnerAudioContext 对象。
    this.innerAudioContext = wx.createInnerAudioContext();
    // 发生错误触发
    this.innerAudioContext.onError(function (res) {})
    //设置音频地址
    switch (key) {
      case 3:
        this.innerAudioContext.src = "/audio/offline.mp3"
        //console.log("离线通知");
        break;
      case 1:
        this.innerAudioContext.src = "/audio/lalram.mp3"
        //console.log("低报通知");
        break;
      //case 2:
      //  this.innerAudioContext.src = "/audio/halram.mp3"
       // console.log("高报通知");
      //  break;
      default:
        break;
    }
    //播放音频
    this.innerAudioContext.play();
    //设置当前播放按钮状态切换
    this.setData({
      isPlay: true
    })
    //console.log("播放了");
  },


  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(){
    
  },
  
  //下拉刷新
  onRefresh(){
    //导航条加载动画
    wx.showNavigationBarLoading()
    //loading 提示框
    wx.showLoading({
      title: 'Loading...',
    })
    this.getDevices() 
    this.offlineInform()
    
    console.log("下拉刷新啦");
    setTimeout(function () {
      wx.hideLoading();
      wx.hideNavigationBarLoading();
      
      //停止下拉刷新
      wx.stopPullDownRefresh();
    }, 1000)
  },


  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady(){
    var that = this
    that.getDevices() 
    that.alarmRecordInit()
    that.setData({
      switchChecked:wx.getStorageSync('switchChecked')
    })
    
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    var that = this
    clearInterval(this.data.timer);
    clearInterval(this.data.timer1);
		this.setData({
			timer:setInterval(function(){   //在这里写需要定时刷新的代码
        if(that.data.switchChecked == true){
          that.getDevices()     
          that.alarmRecord()
        }
      },5*1000),
      timer1:setInterval(function(){   //在这里写需要定时刷新的代码
        if(that.data.switchChecked == true){
          that.offlineInform()
          that.alramInform()
          
          //console.log('以刷新')   
        }
      },1000)
		})
    
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {
    var that = this
    clearInterval(this.data.timer);
    clearInterval(this.data.timer1);
		that.setData({
			timer:setInterval(function(){   //在这里写需要定时刷新的代码
        if(that.data.switchChecked == true){
          that.getDevices()     
        }
      },10000),
      timer1:setInterval(function(){   //在这里写需要定时刷新的代码
        if(that.data.switchChecked == true){
          that.offlineInform()
          that.alramInform()
          //console.log('以刷新')   
        }
      },1000)
		})
    
    
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {
    //var that = this
    clearInterval(this.data.timer);
    clearInterval(this.data.timer1);
		
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {
    this.onRefresh()
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})